package drds.global_transaction.resource_manager.undolog.undo_executor;

import drds.common.ShouldNeverHappenException;
import drds.global_transaction.resource_manager.model.Column;
import drds.global_transaction.resource_manager.model.Image;
import drds.global_transaction.resource_manager.model.KeyType;
import drds.global_transaction.resource_manager.model.Record;
import drds.global_transaction.resource_manager.undolog.UndoLog;

import java.util.List;

public class UpdateUndoExecutor extends UndoExecutor
{

	public UpdateUndoExecutor(UndoLog undoLog)
	{
		super(undoLog);
	}

	@Override
	protected String buildUndoSql()
	{
		Image beforeImage = undoLog.getBeforeImage();
		List<Record> beforeImageRecordList = beforeImage.getRecordList();
		if (beforeImageRecordList == null || beforeImageRecordList.size() == 0)
		{
			throw new ShouldNeverHappenException("invalid undo log");
		}
		Record record = beforeImageRecordList.get(0);
		StringBuilder sb = new StringBuilder("update " + undoLog.getTableName() + " set ");
		StringBuilder where = new StringBuilder(" where ");
		boolean first = true;
		for (Column column : record.getColumnList())
		{
			if (column.getKeyType() == KeyType.primary_key)
			{
				where.append(column.getName() + " = ?");
			} else
			{
				if (first)
				{
					first = false;
				} else
				{
					sb.append(", ");
				}
				sb.append(column.getName() + " = ?");
			}

		}
		return sb.append(where).toString();
	}

	@Override
	protected Image getUndoImage()
	{
		return undoLog.getBeforeImage();
	}
}
